import 'package:flutter/material.dart';
import 'package:flutter_study/mvvm/model/storymodel.dart';
import 'package:flutter_study/mvvm/viewmodel/storylist_viewmodel.dart';

class StoryPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return StoryPageState();
  }
}

class StoryPageState extends State<StoryPage> {
  var storyListViewModel;

  @override
  void initState() {
    storyListViewModel = StoryListViewModel();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        title: Text('MVVM'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            onPressed: () {
              storyListViewModel.addData();
            },
            child: Text('刷新'),
          ),
          Expanded(
              child: StreamBuilder<List<StoryModel>>(
                  stream: storyListViewModel.outStoryListz,
                  builder: (context, snapshot) {
                    List<StoryModel> stories = snapshot.data; // (2)
                    return ListView.builder(
                        itemCount: stories == null
                            ? 0
                            : (stories.length == null ? 0 : stories.length),
                        itemBuilder: (context, index) {
                          if (stories != null && stories.length > 0) {
                            print('===>${index}');
                            return _buildRow(stories[index]);
                          } else {
                            return Text('没有数据');
                          }
                        });
//                        onRefresh: null);
                  })),
        ],
      ),
    );
  }

  Widget _buildRow(story) {
    return Row(
      children: <Widget>[
        Expanded(
          child: Text(story.id),
          flex: 1,
        ),
        Expanded(
          child: Text(story.title),
          flex: 1,
        ),
      ],
    );
  }
}
